package boardgamer.yavalath.client.preference;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.AttributeSet;
import boardgamer.common.client.preference.IconListPreference;
import boardgamer.yavalath.common.YavalathPlayerState;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.EnumSet;
import java.util.List;
import java.util.Set;

import static boardgamer.yavalath.client.Settings.KEY_COLOR_PLAYER_PREFIX;
import static boardgamer.yavalath.client.preference.RegisteredPlayerColorPicker.DEFAULT_PLAYER_COLOR;
import static boardgamer.yavalath.client.preference.RegisteredPlayerColorPicker.PLAYER_COLOR_CONVERTER;
import static boardgamer.yavalath.client.preference.RegisteredPlayerColorPicker.PLAYER_COLOR_RENDERER;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class PlayerColorPickerPreference extends IconListPreference {

  private Integer playerId;
  private SharedPreferences sharedPreferences;
  
  public PlayerColorPickerPreference(Context context) {
    super(context);
  }

  public PlayerColorPickerPreference(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
  }
  
  public void setPlayerId(int playerId) {
    this.playerId = playerId;
  }
  
  public void setSharedPreferences(SharedPreferences sharedPreferences) {
    this.sharedPreferences = checkNotNull(sharedPreferences, "sharedPreferences");
  }

  @Override
  protected void onClick() {
    Set<String> pickedColors = Sets.newHashSet();
    for (int i = 0; i < DEFAULT_PLAYER_COLOR.length; i++) {
      if (i != playerId) {
        pickedColors.add(sharedPreferences.getString(KEY_COLOR_PLAYER_PREFIX + "-" + i,
            DEFAULT_PLAYER_COLOR[i].name()));
      }
    }

    List<String> entryValues = Lists.newArrayList();
    List<String> entries = Lists.newArrayList();
    for (YavalathPlayerState.PlayerColor color : EnumSet.allOf(YavalathPlayerState.PlayerColor.class)) {
      if (!pickedColors.contains(color.name())) {
        entries.add(PLAYER_COLOR_RENDERER.render(color));
        entryValues.add(PLAYER_COLOR_CONVERTER.toString(color));
      }
    }

    setEntries(Iterables.toArray(entries, String.class));
    setEntryValues(Iterables.toArray(entryValues, String.class));

    super.onClick();
  }
}
